class Task
  include Mongoid::Document
  include Mongoid::Timestamps
  field :num_of_fingers, type: Integer
  field :num_of_samples, type: Integer
  field :name, type: String

  has_many :results, dependent: :destroy
  has_many :fingers, dependent: :destroy
  has_many :samples, dependent: :destroy

  after_update :check_need_reset

  def valid_finger_ids
    self.fingers.valid.map(&:id).map(&:to_s)
  end

  def invalid_finger_ids
    self.fingers.invalid.map(&:id).map(&:to_s)
  end

  def reset
    self.fingers.invalid.update_all(marker: 'pending')
  end

  def finished?
    self.fingers.valid.size >= self.num_of_fingers
  end

  def get_view
    text = ""
    self.fingers.valid.each do |finger|
      finger.valid_samples.each do |sample|
        text << sample.uuid << "\n"
      end
    end

    text
  end

  private

  def check_need_reset
    sample_change = self.changes['num_of_samples']
    if sample_change && sample_change[1] > sample_change[0]
      self.reset
    elsif sample_change && sample_change[1] < sample_change[0]
      self.fingers.invalid.each do |f|
        if f.valid_sample_ids.size >= sample_change[1]
          f.update_attributes(marker: 'pending')
        end
      end
    end

    true
  end

end
